package com.nclg.exam.shiro;

import com.nclg.exam.entity.TUser;
import com.nclg.exam.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class TUserRealm extends AuthorizingRealm {

    @Autowired
    private UserService tUserService;

    /**
     * 权限验证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 身份验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1、获取前台传送的用户名
        String uAccount = authenticationToken.getPrincipal().toString();
        TUser tUser = tUserService.selectByAccount(uAccount);
        if (null == tUser){
            return null;
        }
        SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(tUser, tUser.getUPassword(),
                new SimpleByteSource(tUser.getUSalt()), getName());

        return sai;
    }

    @Override
    public void setName(String name) {
        super.setName("tUserRealm");
    }
}
